package com.zwg.test.drools.service;

import com.zwg.test.drools.fact.Fire;
import com.zwg.test.drools.fact.Room;
import com.zwg.test.drools.fact.Sprinkler;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 火灾报警规则
 * @author zwg
 * @date 2018-08-22 21:10
 **/
@Service
public class FireAlarmRuleService {

    /**
     * 有状态和无状态session的使用和区别
     * https://blog.csdn.net/u013815546/article/details/70050315
     *
     * 与无状态会话相反，必须先调用dispose()方法，以确保没有内存泄漏，
     * 因为KieBase包含创建状态知识会话时的引用。 由于状态知识会话是最常用的会话类型，
     * 所以它只是在KIE API中命名为KieSession。
     * KieSession还支持BatchExecutor接口，如StatelessKieSession，
     * 唯一的区别是FireAllRules命令在有状态会话结束时不被自动调用
     *
     */


    @Autowired
    KieSession kieSession;
    public static Map<String,Room> name2room = new HashMap<String,Room>();

    public static Map<String,FactHandle> name2FactHandle = new HashMap<String,FactHandle>();

    public void init(){
        String[] names = new String[]{"kitchen", "bedroom", "office", "livingroom"};

        for( String name: names ){
            Room room = new Room( name );
            name2room.put( name, room );
            kieSession.insert( room );
            Sprinkler sprinkler = new Sprinkler(room);
            kieSession.insert( sprinkler );
        }

        kieSession.fireAllRules();
    }


    public void fire(){
        Fire kitchenFire = new Fire( name2room.get( "kitchen" ) );
        Fire officeFire = new Fire( name2room.get( "office" ) );
        FactHandle kitchenFireHandle = kieSession.insert( kitchenFire );
        name2FactHandle.put("kitchen",kitchenFireHandle);
        FactHandle officeFireHandle = kieSession.insert( officeFire );
        name2FactHandle.put("office",officeFireHandle);

        kieSession.fireAllRules();
    }

    public void fireOff(){
        if(name2FactHandle!=null && !name2FactHandle.isEmpty()){
            for (String name : name2FactHandle.keySet()) {
                kieSession.delete( name2FactHandle.remove(name) );
            }
        }

        kieSession.fireAllRules();
    }


    public void status(){
        kieSession.getFactHandles().parallelStream().forEach(factHandle -> {
            System.out.println("===="+factHandle.toExternalForm());
        });
        kieSession.fireAllRules();
    }



}
